package com.ias.agdis_r.preference;

import java.util.HashSet;
import java.util.Set;

import android.app.AlertDialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.MultiSelectListPreference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * 语音播报设置Preference，代理MultiSelectListPreference的OnItemClickListener，
 * 根据第一项选择状态控制其他项是否处于可选状态；将设置结果以“【数字1】&【数字2】”的学生保存， 其中【数字1】代表TTS开关状态，0为关，1为开。
 * 【数字2 】为TTS_OPEN_TYPE值
 * 
 * @author qibo.yu
 *
 */
public class VoiceEffectPreference extends MultiSelectListPreference implements OnItemClickListener {

	private static final String SPLIT_STRING = "&";
	public static final String DEFAULT_FREFS = "1" + SPLIT_STRING + "31";

	private ListView mListView;
	private boolean[] mCheckedItems;
	private OnItemClickListener supperOnItemClickListener;

	/**
	 * 通过设置获取到对应的TTS开关状态
	 * 
	 * @param prefs
	 * @return
	 */
	public static boolean isTTSOpen(String prefs) {
		if (prefs == null) {
			return false;
		}
		return !prefs.split(SPLIT_STRING)[0].equals("0");
	}

	/**
	 * 获取TTS类型
	 * 
	 * @param prefs
	 * @return
	 */
	public static int getTTSOpenType(String prefs) {
		if (null != prefs && prefs.indexOf(SPLIT_STRING) != -1) {
			return Integer.parseInt(prefs.split(SPLIT_STRING)[1]);
		}
		return 0;
	}

	public VoiceEffectPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public VoiceEffectPreference(Context context) {
		super(context);
	}

	/**
	 * 保存值
	 */
	@Override
	public void setValues(Set<String> values) {
		getValues().clear();
		getValues().addAll(values);

		int sum = 0;
		for (String val : values) {
			try {
				sum += Integer.parseInt(val);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}

		String result = "";
		if (values.contains("0")) {
			result = "0" + SPLIT_STRING + sum;
		} else {
			result = "1" + SPLIT_STRING + sum;
		}
		persistString(result);
		Log.d("C_pref", "persistedString save:" + result);
	}

	@Override
	protected Object onGetDefaultValue(TypedArray a, int index) {
		return DEFAULT_FREFS;
	}

	/**
	 * 读取值
	 */
	@Override
	protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {

		final String persistedString = restoreValue ? getPersistedString(DEFAULT_FREFS) : (String) defaultValue;

		Log.d("C_pref", "persistedString:" + persistedString + ", restoreValue:" + restoreValue);

		String[] splitString = persistedString.split(SPLIT_STRING);

		if (splitString.length != 2) {
			splitString = DEFAULT_FREFS.split(SPLIT_STRING);
		}

		int value = Integer.parseInt(splitString[1]);
		int flag = Integer.parseInt(splitString[0]);

		Set<String> res = new HashSet<String>();

		for (CharSequence sequence : getEntryValues()) {
			try {
				int val = Integer.parseInt(sequence.toString());
				if ((val & value) != 0) {
					res.add(sequence.toString());
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}

		if (flag == 0) {
			res.add("0");
		}

		setValues(res);
	}

	/**
	 * 显示对话框时，实现对父类Item点击事件的代理
	 */
	@Override
	protected void showDialog(Bundle state) {
		super.showDialog(state);
		if (getDialog() instanceof AlertDialog) {
			final AlertDialog dialog = (AlertDialog) getDialog();
			mListView = dialog.getListView();
			if (mListView != null) {
				supperOnItemClickListener = mListView.getOnItemClickListener();

				mCheckedItems = getSelectedItems();

				mListView.setAdapter(getAdapter());
				mListView.setOnItemClickListener(this);
			}
		}
	}

	/**
	 * 获取一个符和业务需求的适配器：第一项选中时其他不可选，否则都可选
	 * 
	 * @return
	 */
	private ListAdapter getAdapter() {

		ListAdapter adapter = new ArrayAdapter<CharSequence>(getContext(), android.R.layout.select_dialog_multichoice,
				android.R.id.text1, getEntries()) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View view = super.getView(position, convertView, parent);
				if (mCheckedItems != null) {
					boolean isItemChecked = mCheckedItems[position];
					if (isItemChecked) {
						mListView.setItemChecked(position, true);
					}

					CheckedTextView checkedTextView = (CheckedTextView) view;

					if (mCheckedItems[0] && position > 0) {
						checkedTextView.setEnabled(false);
						checkedTextView.setClickable(true);
					} else if (position == 0) {
						checkedTextView.setEnabled(true);
						checkedTextView.setClickable(false);
					}
				}
				return view;
			}
		};
		return adapter;
	}

	/**
	 * 获取已被选择的Item
	 * 
	 * @return
	 */
	private boolean[] getSelectedItems() {
		final CharSequence[] entries = getEntryValues();
		final int entryCount = entries.length;
		final Set<String> values = getValues();
		boolean[] result = new boolean[entryCount];

		for (int i = 0; i < entryCount; i++) {
			result[i] = values.contains(entries[i].toString());
		}

		return result;
	}

	/**
	 * 调用代理事件方法，同时修正Item可点击状态
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		supperOnItemClickListener.onItemClick(parent, view, position, id);

		mListView.postInvalidate();

		if (position == 0) {
			CheckedTextView checkedTextView = (CheckedTextView) view;
			for (int i = 1; i < parent.getChildCount(); i++) {
				CheckedTextView childCheckedTextView = (CheckedTextView) parent.getChildAt(i);
				childCheckedTextView.setEnabled(!checkedTextView.isChecked());
				childCheckedTextView.setClickable(checkedTextView.isChecked());
			}
		}
	}

}
